<?php
require_once __DIR__.'/ErrorCode.php';
class Article
{
	private $db;

	/**
	 * Article constructor.
	 *
	 * @param $db
	 */
	public function __construct ( $db )
	{
		$this -> db = $db;
	}

	public function create($title, $content, $userId)
	{
	if (empty( $title)){
		throw new Exception('文章标题不能为空', ErrorCode::ARTICLE_TITLE_CANNOT_EMPTY);
	}
		if (empty( $content)){
			throw new Exception('文章内容不能为空', ErrorCode::ARTICLE_CONTENT_CANNOT_EMPTY);
		}
		$sql = 'INSERT INTO `article`(`title`, `content`, `userId`, `created_at`)
	VALUES(:titile, :content, :userId, :created_at) ';
		$created_at = time();
		$stmt = $this->db->prepare($sql);
		$stmt->bindParam(':title', $title);
		$stmt->bindParam(':content', $content);
		$stmt->bindParam(':userId', $userId);
		$stmt->bindParam(':created_at', $created_at);
		if (!$stmt->execute()){
			throw new Exception('发表文章失败', ErrorCode::ARTICLE_CREATE_FAIL);
		}
		return [
			'articleId' =>  $this->db->lastInsertId(),
		    'title' => $title,
		    'content' => $content,
		    'userId' => $userId,
		    'created_at' => $created_at,
		];


	}

	public function view($articleId)
	{
		if (empty( $articleId)){
			throw new Exception('文章id不能为空', ErrorCode::ARTICLE_ID_CANNOT_EMPTY);
		}
		$sql = 'SELECT * FROM `article` WHERE `articleId`=:id';
		$stmt = $this->$db->prepare($sql);
		$stmt->bindParam(':id', $articleId);
		$stmt->execute();
		$article = $stmt->fetch(PDO::FETCH_ASSOC);
		if (empty( $article)){
			throw new Exception('文章不存在', ErrorCode::ARTICLE_NOT_FOUND);
			return $article;
		}
	}

	public function edit($articleId, $title, $content, $userId)
	{
		$article = $this->view( $articleId);
		if ($article['userId'] !== $userId) {
			throw new Exception('您无权编辑该文章', ErrorCode::PERMISSION_DENIED);
		}
		$title = empty( $title) ? $title['title'] : $title;
		$content = empty( $content) ? $content['content'] : $content;
		if ($title === $article['title']  && $content === $content['content']) {
			return $article;
		}



	}

	public function delete($articleId, $userId)
	{

	}

	public function getList($userId, $page = 1, $size = 10)
	{

	}
}